import { setupServer } from 'msw/node';
import { rest } from 'msw';

// 模拟 API 响应
export const handlers = [
  // 模拟应用信息 API
  rest.post('/api/get_app_info', (req, res, ctx) => {
    return res(
      ctx.json({
        name: 'Tauri Modern Template',
        version: '1.0.0',
        tauri_version: '2.0.0',
        identifier: 'com.modern.tauri-template',
      })
    );
  }),

  // 模拟系统信息 API
  rest.post('/api/get_system_info', (req, res, ctx) => {
    return res(
      ctx.json({
        platform: 'linux',
        arch: 'x86_64',
        version: 'Ubuntu 22.04',
        hostname: 'test-machine',
        uptime: 3600,
        total_memory: 8589934592,
        free_memory: 4294967296,
        cpu_count: 8,
        load_average: [0.5, 0.6, 0.7],
      })
    );
  }),

  // 模拟配置 API
  rest.post('/api/get_app_config', (req, res, ctx) => {
    return res(
      ctx.json({
        id: 'default',
        theme: 'system',
        language: 'zh-CN',
        auto_start: false,
        minimize_to_tray: true,
        notifications: true,
        shortcuts: '{"toggleWindow":"CmdOrCtrl+Shift+H","newItem":"CmdOrCtrl+N","search":"CmdOrCtrl+F"}',
        created_at: '2024-01-01T00:00:00Z',
        updated_at: '2024-01-01T00:00:00Z',
      })
    );
  }),

  rest.post('/api/set_app_config', (req, res, ctx) => {
    return res(ctx.json({ success: true }));
  }),

  // 模拟测试命令
  rest.post('/api/test_command', (req, res, ctx) => {
    return res(
      ctx.json({
        message: 'Hello from Rust backend!',
        timestamp: new Date().toISOString(),
        echo: 'Test message',
      })
    );
  }),

  // 模拟文件操作
  rest.post('/api/read_text_file', (req, res, ctx) => {
    return res(ctx.text('Mock file content'));
  }),

  rest.post('/api/write_text_file', (req, res, ctx) => {
    return res(ctx.json({ success: true }));
  }),

  rest.post('/api/file_exists', (req, res, ctx) => {
    return res(ctx.json(true));
  }),

  // 模拟窗口管理
  rest.post('/api/toggle_window_visibility', (req, res, ctx) => {
    return res(ctx.json(true));
  }),

  rest.post('/api/center_window', (req, res, ctx) => {
    return res(ctx.json(true));
  }),

  // 模拟日志 API
  rest.post('/api/get_logs', (req, res, ctx) => {
    return res(
      ctx.json([
        {
          id: '1',
          level: 'info',
          message: 'Application started',
          module: 'main',
          file: 'main.rs',
          line: 10,
          created_at: '2024-01-01T00:00:00Z',
        },
        {
          id: '2',
          level: 'error',
          message: 'Test error message',
          module: 'test',
          file: 'test.rs',
          line: 20,
          created_at: '2024-01-01T00:01:00Z',
        },
      ])
    );
  }),

  rest.post('/api/clear_logs', (req, res, ctx) => {
    return res(ctx.json(5)); // 返回删除的日志数量
  }),

  // 模拟工具函数
  rest.post('/api/generate_uuid', (req, res, ctx) => {
    return res(ctx.text('550e8400-e29b-41d4-a716-446655440000'));
  }),

  rest.post('/api/get_current_timestamp', (req, res, ctx) => {
    return res(ctx.text(new Date().toISOString()));
  }),

  // 错误处理测试
  rest.post('/api/error_test', (req, res, ctx) => {
    return res(
      ctx.status(500),
      ctx.json({ error: 'Internal server error' })
    );
  }),

  // 网络延迟测试
  rest.post('/api/slow_request', (req, res, ctx) => {
    return res(
      ctx.delay(2000),
      ctx.json({ message: 'Slow response' })
    );
  }),
];

// 创建服务器实例
export const server = setupServer(...handlers);

// 错误处理器
export const errorHandlers = [
  rest.post('/api/*', (req, res, ctx) => {
    return res(
      ctx.status(500),
      ctx.json({ error: 'Mock server error' })
    );
  }),
];

// 空响应处理器
export const emptyHandlers = [
  rest.post('/api/*', (req, res, ctx) => {
    return res(ctx.json(null));
  }),
];

// 延迟响应处理器
export const delayedHandlers = handlers.map(handler => {
  return rest.post(handler.info.path, (req, res, ctx) => {
    return res(
      ctx.delay(1000),
      ctx.json({ delayed: true })
    );
  });
});

// 测试工具函数
export const mockTauriCommand = (command: string, response: any, shouldFail = false) => {
  const handler = rest.post(`/api/${command}`, (req, res, ctx) => {
    if (shouldFail) {
      return res(
        ctx.status(500),
        ctx.json({ error: 'Command failed' })
      );
    }
    return res(ctx.json(response));
  });

  server.use(handler);
  return handler;
};

export const resetServerHandlers = () => {
  server.resetHandlers(...handlers);
};

export const useErrorHandlers = () => {
  server.use(...errorHandlers);
};

export const useEmptyHandlers = () => {
  server.use(...emptyHandlers);
};

export const useDelayedHandlers = () => {
  server.use(...delayedHandlers);
};
